//
//  InstallerSignForNewStcFormVC.swift
//  ezyform
//
//  Created by Moennig Q on 6/5/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import AVFoundation
import MBProgressHUD
import CoreLocation
class InstallerSignForNewStcFormVC: BaseViewController {
    let customView = InstallerSignForNewStcFormView(customBackToPreFlag: true)
    var model: PVDDetailModel?
    //前置摄像头拍照
    var session: AVCaptureSession?
    var output: AVCapturePhotoOutput?
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        self.initUI()
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .authorized { /****已授权，可以打开相机且installer或owner才自拍****/
            setupInputOutput()
        }
        Tool().requestCurrentLocation()
    }
    func initUI(){
        //view
        self.view = self.customView
        self.customView.backToPreBtn.addTarget(self, action: #selector(backToPreVieController), for: UIControl.Event.touchUpInside)
        self.customView.setTitleInfo(APPConfig.loginInfo.currentSignatureType.rawValue + " Signature")
        
        if let model = self.model{
            self.customView.setData(model.signatures.installer_full_name,accreditedName: model.signatures.installer_accredited_number)
        }
        self.customView.selectWitnessView.selectWitnessClosure = { [weak self] in
            guard let strongSelf = self else { return  }
            guard let _ = strongSelf.model else {
                return
            }
            //检查是否已签名
            if !strongSelf.customView.signView.signaturedFlag {
                Tool().showAlertViewWithOneBtn(message: R.string.localizable.pleaseSignBeforeSaving())
                return
            }
            if let _ = strongSelf.output,let _ = strongSelf.session {
                let settings = AVCapturePhotoSettings()
                strongSelf.output!.capturePhoto(with: settings, delegate: strongSelf)
            }else{
                strongSelf.saveSignature()
            }
            
        }
    }
    @objc func backToPreVieController() {
        Tool().showAlertViewWithTwoBtns(message: R.string.localizable.pvdDetailSignaturesSignatureBackfromsignTip(),  yesClosure: {[weak self] in
            self?.navigationController?.popViewController(animated: false)
        })
    }
    //Get the device (Front or Back)
    func getDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: position)
        let devices = deviceDiscoverySession.devices
        if devices.count > 0 {
            return devices[0]
        }
        return nil
    }
    func setupInputOutput(){
        if let camera = getDevice(position: .front) {
            do {
                self.session = AVCaptureSession()
                self.output = AVCapturePhotoOutput()
                guard let _ = self.session,let _ = output  else {
                    return
                }
                self.session!.beginConfiguration()
                //如果session包括AVCapturePhotoOutput对象，session会自动尝试启用wide-color，有些设备(iPad)并不支持activeFormat.supportedColorSpaces，这是个AVCaptureSession的坑
                self.session!.automaticallyConfiguresCaptureDeviceForWideColor = false
                let input = try AVCaptureDeviceInput(device: camera)
                if self.session!.canAddInput(input){
                    self.session!.addInput(input)
                }
                
                output!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg] )], completionHandler: nil)
                session!.sessionPreset = .photo
                if session!.canAddOutput(output!){
                    session!.addOutput(output!)
                }
                self.session!.commitConfiguration()
            }catch{
                print(error)
            }
            
        }
    }
    func saveSignature(_ signData: Data? = nil){
        guard let _ = self.model else {
            return
        }
        var signSelfiData: Data?
        //转换为竖屏方向
        if let data = signData {
            signSelfiData = MediaUtil().normalizedImage(data)
        }
            
        let image = self.customView.signView.getSignature()
        
        if let imageData = image.pngData() {
            APPConfig.loginInfo.signatureInfoModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            //签名图片
            let signedAt = DateUtil().getCurrentDatetime()
            APPConfig.loginInfo.signatureInfoModel.installer_sign_imagedata = NSData(data: imageData)
            APPConfig.loginInfo.signatureInfoModel.installer_signed_at = signedAt
            //经纬度
            APPConfig.loginInfo.signatureInfoModel.installer_signature_latitude = APPConfig.currentLocation.latitude
            APPConfig.loginInfo.signatureInfoModel.installer_signature_longitude = APPConfig.currentLocation.longitude
            
            //sign selfe
            if let data = signSelfiData {
                let originImageData = MediaUtil().resetSizeOfImageData(source_image: UIImage(data: data),maxSize: 100)
                APPConfig.loginInfo.signatureInfoModel.installer_signature_selfie = originImageData
            }
            
            //如果是installer&Designer一起签的，designer的签字和installer签名图片一样
            if APPConfig.loginInfo.currentSignatureType == .InstallerAndDesiger {
                APPConfig.loginInfo.signatureInfoModel.designer_sign_imagedata = NSData(data: imageData)
                APPConfig.loginInfo.signatureInfoModel.designer_signed_at = signedAt
            }
            if self.customView.selectWitnessView.ownerAsWitnessFlag{//选择owner作为witness
                let vc = OnlineStatementViewController(statementType: .Owner)
                self.navigationController?.pushViewController(vc, animated: false)
            }else{//other作为witness
                let vc = WitnessSignForNewStcFormVC()
                self.navigationController?.pushViewController(vc, animated: false)
            }
        }else{
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.signatures.signature.save.faild", comment: ""))
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        if let _ = self.session {
            DispatchQueue.global(qos: .background).async {
                self.session!.startRunning()
            }
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let _ = self.session {
            self.session!.stopRunning()
        }
    }
    deinit {
        //尽可能释放无用的内存
        self.session = nil
        self.output = nil
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }

}
extension InstallerSignForNewStcFormVC: AVCapturePhotoCaptureDelegate{
    @available(iOS 11.0, *)
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let _ = self.session{
            self.session!.stopRunning()
        }
        
        if let _ = error{
            let errMsg = "Installer sign and can not take selfi, the reason: " + error!.localizedDescription
            AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
            self.saveSignature()
        }else{
            if let imageData = photo.fileDataRepresentation() {
                self.saveSignature(imageData)
            }else{
                let errMsg = "Installer sign and can not take selfi, the reason: photo.fileDataRepresentation() not working"
                AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
                self.saveSignature()
            }
        }
    }
}
